package com.bestcem.xm.ticket.service.impl;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.ticket.controller.vo.RespondentVO;
import com.bestcem.xm.ticket.dao.AlertRecordDao;
import com.bestcem.xm.ticket.entity.mongo.Record;
import com.bestcem.xm.ticket.enums.SurveyTitleTypeEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketMemberGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketSurveyGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
import com.bestcem.xm.ticket.grpc.client.dto.survey.MemberNodeDTO;
import com.bestcem.xm.ticket.grpc.client.dto.survey.RespondentDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupDTO;
import com.bestcem.xm.ticket.service.AlertRecordService;
import com.bestcem.xm.ticket.service.dto.RecordDTO;
import com.bestcem.xm.ticket.service.dto.user.OptionDTO;
import com.bestcem.xm.ticket.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.bestcem.xm.ticket.util.CheckUtil.QTYPE;

/**
 * DS_TICKET_DAO 从工单迁移过来的record表
 *
 * @author jy.zhao
 * @version 1.0
 * @date 2021/8/19 17:07
 **/
@Slf4j
@Repository
public class AlertRecordServiceImpl implements AlertRecordService {

    @Resource
    private AlertRecordDao alertRecordDao;

    @Resource
    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;
    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;
    @Resource
    private TicketSurveyGrpcService ticketSurveyGrpcService;
    @Resource
    private TicketMemberGrpcService ticketMemberGrpcService;
    @Resource
    private CheckUtil checkUtil;

    @Override
    public String saveRecordInfo(Record entity) {
        Record record = alertRecordDao.saveTicketRecord(entity);
        if (Validator.isNull(record)) {
            return null;
        }
        return record.getId();
    }

    /**
     * 获取预警记录
     * 当url指定id时，直接查询该id的预警记录，忽略其他筛选参数
     * 当url没有指定id时，返回分页查询结果，参数在query中
     *
     * @param id
     * @return TicketRecordVO
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/26
     */
    @Override
    public ServiceResult<RecordDTO> getRecordInfo(String id, String userId, String orgId) {
        if (ObjectUtils.isEmpty(id)) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST, "预警id不能为空");
        }
        Record record = alertRecordDao.findById(id);
        if (Objects.isNull(record)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "预警记录不存在");
        }
        RecordDTO recordDTO = parseRecord(record, false, false);
        RespondentDTO respondent = ticketSurveyGrpcService.getRespondentBySeq(recordDTO.getRspdSeq(), recordDTO.getQProjectId());
        if (Objects.isNull(respondent)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "Respondent[seq={" + recordDTO.getRspdSeq() + "}] not found");
        }
        QdesDTO qdesProject = ticketBaseQdesGrpcService.getQdesProject(respondent.getProjectId());
        if (Objects.isNull(qdesProject)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "Project[id={" + respondent.getProjectId() + "}] not found");
        }
        respondent = ticketSurveyGrpcService.getFilledRespondentInfo(respondent, userId, orgId);
        Double score = ticketSurveyGrpcService.getAnswerScoreBySeq(recordDTO.getRspdSeq(), recordDTO.getQProjectId());
        if (Objects.nonNull(score)) {
            respondent.setScore(score);
        }
        RespondentDTO oldRespondent = ticketSurveyGrpcService.getRespondent(recordDTO.getRspdSeq(), true,
                false, true, null, true, userId, recordDTO.getQProjectId());
        List<Map<String, Object>> answers = new ArrayList<>();

        if (Objects.nonNull(oldRespondent) && Objects.nonNull(oldRespondent.getAnswers())) {
            try {
                if (log.isInfoEnabled()) {
                    log.debug("[ticket] getAlertRecord oldRespondent：answers={}", oldRespondent);
                }
                if (Objects.nonNull(oldRespondent.getAnswers())) {
                    JSONArray jsonArray = (JSONArray) JSONArray.parse(oldRespondent.getAnswers());
                    if (!jsonArray.isEmpty()) {
                        for (Object object : jsonArray) {
                            if (Objects.nonNull(object)) {
                                answers.add(((JSONObject) object).getInnerMap());
                            }
                        }
                        if (Objects.nonNull(record.getData())) {
                            JSONObject dataJson = record.getData();
                            if (!answers.isEmpty() && Objects.nonNull(dataJson.getInnerMap())) {
                                // 解析答卷
                                parseRecordAnswers(answers, dataJson.getInnerMap());
                                if (log.isDebugEnabled()) {
                                    log.debug("[ticket] getAlertRecord oldRespondent：answers new{}", answers.toString());
                                }
                            }
                        }
                    }
                }
                if (log.isInfoEnabled()) {
                    log.info("[ticket] getAlertRecord oldRespondent end");
                }
                RespondentVO respondentVO = RespondentVO.DtoToVO(respondent);
                respondentVO.setAnswers(answers);
                // 设置外部参数
                if (StringUtils.isNotEmpty(oldRespondent.getExtParams())) {
                    JSONArray extra = JSONObject.parseArray(oldRespondent.getExtParams());
                    respondentVO.setExt(extra);
                    if (log.isInfoEnabled()) {
                        log.info("[ticket] getAlertRecord oldRespondent extra:{}", extra);
                    }
                }
                recordDTO.setRspd(respondentVO);
            } catch (Exception e) {
                log.error("parse respondent failed", e);
            }
        }
        return ServiceResult.success(recordDTO);
    }

    /**
     * 预警记录处理
     *
     * @param record      预警记录
     * @param withoutData 结果是否清除 data 字段
     * @param withRspd    结果是否附加答卷信息
     * @return 处理过的预警记录
     */
    public RecordDTO parseRecord(Record record, boolean withoutData, boolean withRspd) {
        RecordDTO recordDTO = RecordDTO.getInstance(record);
        QdesDTO qdesProject = ticketBaseQdesGrpcService.getQdesProject(record.getQProjectId());
        recordDTO.setQProject(qdesProject);
        List<String> groupList = recordDTO.getGroupList();
        RecordDTO.Group group = new RecordDTO.Group();
        if (!CollectionUtils.isEmpty(groupList)) {
            GroupDTO groupDTO = ticketBaseUserGrpcService.getGroup(groupList.get(0));
            if (Objects.nonNull(groupDTO)) {
                if (log.isInfoEnabled()) {
                    log.info("[ticket] getAlertRecord parseRecord group {}", groupDTO.getTitle());
                }
                group.setCode(groupDTO.getCode());
                group.setName(groupDTO.getTitle());
            }
        }
        recordDTO.setGroup(group);
        if (withRspd) {
            RespondentDTO respondent = ticketSurveyGrpcService.getRespondentBySeq(recordDTO.getRspdSeq(), recordDTO.getQProjectId());
            if (Objects.nonNull(respondent)) {
                if (log.isInfoEnabled()) {
                    log.info("[ticket] getAlertRecord parseRecord respondent{}", respondent.getSeq());
                }
                respondent.setGroupCode(recordDTO.getGroupCode());
                if (!ObjectUtils.isEmpty(respondent.getMemberId())) {
                    // respondent.member = await rpc.get_member(respondent.member_id)
                    MemberNodeDTO memberDTO = ticketMemberGrpcService.getMemberById(respondent.getMemberId());
                    if (Objects.nonNull(memberDTO)) {
                        if (log.isInfoEnabled()) {
                            log.info("[ticket] getAlertRecord oldRespondent memberDTO{}", memberDTO.getName());
                        }
                        respondent.setMember(memberDTO);
                    }
                }
            }

            recordDTO.setRspd(RespondentVO.DtoToVO(respondent));
        }
        if (withoutData) {
            recordDTO.setData(null);
        }
        return recordDTO;
    }

    /**
     * 获取预警记录的答卷详情
     *
     * @param answers
     * @param recordData
     * @return void
     * @author gy.liu
     * @date 2021/8/26
     */
    public List<Map<String, Object>> parseRecordAnswers(List<Map<String, Object>> answers,
                                                        Map<String, Object> recordData) {
        if (Objects.isNull(answers)) {
            log.error("[Ticket] parse answer is null");
            return null;
        }

        try {

            for (Map<String, Object> answer : answers) {
                // 只匹配工单规则中配置的问题选项
                String gid = String.valueOf(answer.get("gid"));
                if (!recordData.containsKey(gid)) {
                    continue;
                }
                List<Map<String, Object>> realDataList = new ArrayList<>();
                Object o = recordData.get(gid);
                if (o instanceof Collection) {
                    realDataList = new ArrayList<>((List) o);
                }

                Set<String> ruleSet = new HashSet<>();
                List<Map<String, Object>> wordRangeList = new ArrayList<>();

                for (Map<String, Object> item : realDataList) {

                    String ruleId = String.valueOf(item.get("ruleID"));
                    if (!ObjectUtils.isEmpty(ruleId)) {
                        ruleSet.add(ruleId);
                    }

                    Integer operation = Integer.parseInt(String.valueOf(item.get("operation")));
                    if (Objects.isNull(operation)) {
                        continue;
                    }

                    // 危险词处理
                    if (operation.equals(SurveyTitleTypeEnum.WORD.getIndex()) && item.containsKey("data")) {
                        if (item.get("data") instanceof Map) {
                            JSONObject temp = (JSONObject) JSON.toJSON(item.get("data"));
                            wordRangeList.add(temp.getInnerMap());
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.SINGLE.getIndex())
                            || operation.equals(SurveyTitleTypeEnum.MULTIPLE.getIndex())
                            || operation.equals(SurveyTitleTypeEnum.SELECT.getIndex())) {
                        // 选中
                        Integer seq = null;
                        String qType = (String) answer.get("qtype");
                        List<Map<String, Object>> selected = new ArrayList<>();
                        if (Objects.nonNull(item.get("seq"))) {
                            seq = Integer.parseInt(String.valueOf(item.get("seq")));
                        }
                        if (Objects.nonNull(item.get("data"))) {
                            List<Object> ops = new ArrayList<>();
                            Object temp = item.get("data");
                            if (temp instanceof Collection) {
                                ops.addAll((Collection<Object>) temp);
                            }
                            for (Object op : ops) {
                                if (op instanceof Map) {
                                    // 如果是map直接赋值
                                    Map<String, Object> opMap = new HashMap<>((Map) op);
                                    Map<String, Object> opNew = new HashMap<>();
                                    if (opMap.get("row_id") instanceof String) {
                                        String rowId = (String) opMap.get("row_id");
                                        opNew.put("rowId", rowId);
                                    }
                                    if (opMap.get("option_id") instanceof Integer) {
                                        Integer optionId = (Integer) opMap.get("option_id");
                                        opNew.put("optionId", optionId);
                                    } else if (opMap.get("option_id") instanceof String) {
                                        String optionId = (String) opMap.get("option_id");
                                        opNew.put("optionId", optionId);
                                    }
                                    selected.add(opNew);
                                } else {
                                    Map<String, Object> select = new HashMap<>();
                                    select.put("optionId", op);
                                    select.put("rowId", seq);
                                    selected.add(select);
                                }
                            }
                        }
                        List<OptionDTO> selOptions = new ArrayList<>();
                        // answer的遍历从1开始
                        // 根据不同类型组装答案列表
                        if (Objects.nonNull(answer.get("answer")) && answer.get("answer") instanceof List) {
                            if (qType.equals(QTYPE.get(0)) || qType.equals(QTYPE.get(1))) {
                                List<String> anserList = new ArrayList<>();
                                Object temp = answer.get("answer");
                                if (temp instanceof Collection) {
                                    anserList.addAll((Collection<String>) temp);
                                }
                                if (anserList.size() >= 2) {
                                    for (int i = 0; i < anserList.size(); i++) {
                                        OptionDTO selOption = new OptionDTO();
                                        selOption.setAns(anserList.get(i));
                                        selOption.setRowId(++i);
                                        --i;
                                        selOptions.add(selOption);
                                    }
                                }
                            } else if (Objects.nonNull(seq) && seq > 0) {
                                List<Map<String, Object>> anserList = new ArrayList<>();
                                Object temp = answer.get("answer");
                                if (temp instanceof Collection) {
                                    anserList.addAll((Collection<Map<String, Object>>) temp);
                                }
                                for (Map<String, Object> stringObjectMap : anserList) {
                                    if (stringObjectMap.get("seq").equals(seq)) {
                                        if (Objects.nonNull(stringObjectMap.get("answer"))) {
                                            List<Object> selList = new ArrayList<>();
                                            temp = stringObjectMap.get("answer");
                                            if (temp instanceof Collection) {
                                                selList.addAll((Collection<Object>) temp);
                                            }
                                            for (Object sel : selList) {
                                                OptionDTO selOption = new OptionDTO();
                                                selOption.setRowId(seq);
                                                Map<String, Object> seqMap = new HashMap<>();
                                                seqMap.put("seq", sel);
                                                selOption.setAns(seqMap);
                                                selOptions.add(selOption);
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (Objects.nonNull(answer.get("answer")) && answer.get("answer") instanceof List) {
                                    List<Map<String, Object>> anserList = new ArrayList<>();
                                    Object temp = answer.get("answer");
                                    if (temp instanceof Collection) {
                                        anserList.addAll((Collection<Map<String, Object>>) temp);
                                    }
                                    for (Map<String, Object> anser : anserList) {
                                        if (Objects.nonNull(anser.get("seq"))) {
                                            Integer rowId = Integer.parseInt(String.valueOf(anser.get("seq")));
                                            if (Objects.nonNull(anser.get("answer")) && anser.get("answer") instanceof List) {
                                                // 矩阵
                                                List<Map<String, Object>> rowAnswer = (List<Map<String, Object>>) anser.get("answer");
                                                for (Map<String, Object> rowMap : rowAnswer) {
                                                    OptionDTO selOption = new OptionDTO();
                                                    selOption.setRowId(rowId);
                                                    selOption.setAns(rowMap);
                                                    selOptions.add(selOption);
                                                }
                                            } else {
                                                OptionDTO selOption = new OptionDTO();
                                                selOption.setRowId(rowId);
                                                selOption.setAns(anser);
                                                selOptions.add(selOption);
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (Objects.nonNull(answer.get("answer")) && answer.get("answer") instanceof Map) {
                            // 评价题处理
                            if (qType.equals(QTYPE.get(2))) {
                                Map<String, Object> answerMap = new HashMap<>();
                                Object temp = answer.get("answer");
                                if (temp instanceof Map) {
                                    answerMap.putAll((Map) temp);
                                }
                                if (Objects.nonNull(answerMap) && Objects.nonNull(answerMap.get("tagsId")) && answerMap.get("tagsId") instanceof List) {
                                    List<Object> tags = new ArrayList<>();
                                    temp = answerMap.get("tagsId");
                                    if (temp instanceof Collection) {
                                        tags.addAll((Collection<Object>) temp);
                                    }
                                    for (Object tag : tags) {
                                        OptionDTO selOption = new OptionDTO();
                                        selOption.setSeq(tag);
                                        selOptions.add(selOption);
                                    }
                                }
                            }
                        }
                        // 处理行号和答案的列表
                        if (!CollectionUtils.isEmpty(selOptions) && !CollectionUtils.isEmpty(selected)) {
                            // 答案是列表
                            List<Object> ansList = new ArrayList<>();
                            if (answer.get("answer") instanceof List) {
                                ansList = (List<Object>) answer.get("answer");
                            } else if (answer.get("answer") instanceof Map) {
                                // 答案是map
                                Map<String, Object> ansMap = (Map<String, Object>) answer.get("answer");
                                ansList.add(ansMap);
                            }
                            boolean flag = false;
                            for (int i = 0; i < ansList.size(); i++) {
                                if (flag) {
                                    break;
                                }
                                Object ans = ansList.get(i);
                                for (Map<String, Object> select : selected) {
                                    if (flag) {
                                        break;
                                    }
                                    for (OptionDTO selOption : selOptions) {
                                        if (flag) {
                                            break;
                                        }
                                        String rowId = String.valueOf(select.get("row_id"));
                                        if (ObjectUtils.isEmpty(rowId) || "null".equals(rowId)) {
                                            rowId = String.valueOf(select.get("rowId"));
                                        }
                                        if (selOption.getAns() instanceof String) {
                                            String optionId = String.valueOf(select.get("option_id"));
                                            if (ObjectUtils.isEmpty(optionId) || "null".equals(optionId)) {
                                                optionId = String.valueOf(select.get("optionId"));
                                            }
                                            String ansString = "";
                                            if (ans instanceof String) {
                                                ansString = (String) ans;
                                            }
                                            if (StringUtils.isNotEmpty(rowId) && Objects.nonNull(selOption.getRowId())) {
                                                if (optionId.equals(String.valueOf(selOption.getAns())) && rowId.equals(String.valueOf(selOption.getRowId())) && ansString.equals(optionId)) {
                                                    if (qType.equals(QTYPE.get(0))) {
                                                        // 城市题
                                                        Map<String, Object> rowMap = new HashMap<>();
                                                        rowMap.put("v", String.valueOf(selOption.getAns()));
                                                        rowMap.put("marker", true);
                                                        ans = rowMap;
                                                        ansList.set(i, ans);
                                                        flag = true;
                                                    } else if (qType.equals(QTYPE.get(2))) {
                                                        // 旧版评价题 目前不用
                                                        Map<String, Object> rowMap = new HashMap<>();
                                                        rowMap.put("v", selOption);
                                                        rowMap.put("marker", true);
                                                        //ans.put("tags", tags);
                                                    }
                                                }
                                            }
                                        } else {
                                            if (ans instanceof Map) {
                                                Integer optionId = null;
                                                if (select.containsKey("optionId")) {
                                                    optionId = Integer.parseInt(String.valueOf(select.get("optionId")));
                                                }
                                                Map<String, Object> ansMap = (Map<String, Object>) ans;
                                                // 新版评价题
                                                if (qType.equals(QTYPE.get(2))) {
                                                    if (Objects.nonNull(ansMap) && ansMap.get("tagsId") instanceof List) {
                                                        List<Object> tags = (List<Object>) ansMap.get("tagsId");
                                                        for (int j = 0; j < tags.size(); j++) {
                                                            if (Objects.nonNull(tags.get(j))) {
                                                                String v = String.valueOf(tags.get(j));
                                                                if (Objects.nonNull(selOption.getSeq())) {
                                                                    String seqV = String.valueOf(selOption.getSeq());
                                                                    if (v.equals(seqV) && seqV.equals(String.valueOf(optionId))) {
                                                                        Map<String, Object> rowMap = new HashMap<>();
                                                                        rowMap.put("v", selOption.getSeq());
                                                                        rowMap.put("marker", true);
                                                                        tags.set(j, rowMap);
                                                                        //flag = true;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        // 给ans赋值
                                                        //ansList.set(i, tags);
                                                    }
                                                } else {
                                                    List<Map<String, Object>> ansList1 = new ArrayList<>();
                                                    if (Objects.nonNull(ansMap.get("answer")) && ansMap.get("answer") instanceof List) {
                                                        ansList1 = (List<Map<String, Object>>) ansMap.get("answer");
                                                    } else {
                                                        // 单选，多选没有answer
                                                        ansList1.add(ansMap);
                                                    }
                                                    if (ansList1.size() > 0) {
                                                        for (Map<String, Object> ansMap1 : ansList1) {
                                                            if (selOption.getAns() instanceof Map) {
                                                                Map<String, Object> selMap = (Map<String, Object>) selOption.getAns();
                                                                String seqNew = String.valueOf(selMap.get("seq"));
                                                                String gidNew = String.valueOf(selMap.get("gid"));
                                                                String gidOld = String.valueOf(ansMap1.get("gid"));
                                                                if (Objects.isNull(gidNew) || Objects.isNull(gidOld) || !gidOld.equals(gidNew)) {
                                                                    continue;
                                                                }
                                                                String optionIdStr = String.valueOf(optionId);
                                                                // 矩阵多选题
                                                                if (StringUtils.isNotEmpty(rowId) && !"null".equals(rowId) && StringUtils.isNotEmpty(optionIdStr)) {
                                                                    if ((optionIdStr.equals(seqNew)) && rowId.equals(String.valueOf(selOption.getRowId()))) {
                                                                        ansMap1.put("marker", true);
                                                                        //flag = true;
                                                                    }
                                                                } else {
                                                                    // 单选 多选
                                                                    if ((optionIdStr.equals(seqNew))) {
                                                                        ansMap1.put("marker", true);
                                                                        //flag = true;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.EXIST.getIndex())) {
                        // 非空处理
                        if (item.get("data") instanceof Map) {
                            wordRangeList.add((Map<String, Object>) item.get("data"));
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.SCORE_RANGE.getIndex())
                            || operation.equals(SurveyTitleTypeEnum.AVERAGE.getIndex())
                            || operation.equals(SurveyTitleTypeEnum.SUM.getIndex())) {
                        Map<Object, Object> markerPos = new HashMap<>();
                        // 打分题处理
                        if (Objects.nonNull(item.get("data")) && item.get("data") instanceof List) {
                            List<Map<String, Object>> itemList = (List<Map<String, Object>>) item.get("data");
                            if (itemList.size() > 0) {
                                for (Map<String, Object> itemData : itemList) {
                                    if (Objects.nonNull(itemData.get("rid"))) {
                                        Map<Object, Object> rowMap = new HashMap<>();
                                        rowMap.put(itemData.get("oid"), true);
                                        markerPos.put(itemData.get("rid"), rowMap);
                                    } else {
                                        if (Objects.nonNull(itemData.get("oid"))) {
                                            markerPos.put(itemData.get("oid"), true);
                                        }
                                    }
                                }
                            }
                        }
                        if (answer.get("answer") instanceof Map) {
                            Map<String, Object> anserMap = (Map<String, Object>) answer.get("answer");
                            if (Objects.nonNull(anserMap.get("score")) && (Objects.nonNull(anserMap.get("tags")) || Objects.nonNull(anserMap.get("tagsId")))) {
                                // 评价题
                                anserMap.put("marker", true);
                                if (markerPos.containsKey("score")) {
                                    Map<String, Object> scoreMap = new HashMap<>();
                                    scoreMap.put("v", anserMap.get("score"));
                                    scoreMap.put("marker", true);
                                    anserMap.put("score", scoreMap);
                                }
                            }
                        } else {
                            if (answer.get("answer") instanceof List) {
                                List<Map<String, Object>> answerList = (List<Map<String, Object>>) answer.get("answer");
                                if (answerList.size() > 0) {
                                    for (Map<String, Object> option : answerList) {
                                        if (Objects.nonNull(option.get("score")) && option.get("seq") instanceof Integer) {
                                            Integer seq = Integer.parseInt(String.valueOf(option.get("seq")));
                                            if (markerPos.containsKey(String.valueOf(seq))) {
                                                option.put("marker", true);
                                            }
                                        } else {
                                            // 矩阵打分题
                                            if (option.get("gid") instanceof Integer) {
                                                Integer gidNew = Integer.parseInt(String.valueOf(option.get("gid")));
                                                if (markerPos.containsKey(String.valueOf(gidNew))) {
                                                    Map<String, Object> seqs = (Map<String, Object>) markerPos.get(String.valueOf(gidNew));
                                                    if (Objects.nonNull(option.get("answer"))) {
                                                        List<Map<String, Object>> options = (List<Map<String, Object>>) option.get("answer");
                                                        if (options.size() > 0) {
                                                            for (Map<String, Object> ans : options) {
                                                                if (Objects.nonNull(seqs) && seqs.containsKey(String.valueOf(ans.get("seq")))) {
                                                                    ans.put("marker", true);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.DATE.getIndex())) {
                        // 日期处理
                        if (answer.get("answer") instanceof Map) {
                            Map<String, Object> ansMap = (Map<String, Object>) answer.get("answer");
                            ansMap.put("marker", true);
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.TIME.getIndex())) {
                        // 时间题处理
                        if (Objects.nonNull(answer.get("answer"))) {
                            if (answer.get("answer") instanceof Map) {
                                // ts为int则标记true
                                Map<String, Object> ansMap = (Map<String, Object>) answer.get("answer");
                                if (ansMap.get("ts") instanceof Integer) {
                                    ansMap.put("marker", true);
                                }
                            } else if (answer.get("answer") instanceof Integer) {
                                Map<String, Object> markerMap = new HashMap<>();
                                markerMap.put("ts", answer.get("answer"));
                                markerMap.put("marker", true);
                                answer.put("answer", markerMap);
                            }
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.CLASSIFY.getIndex())) {
                        // 分类处理
                        List<Map<String, Object>> answerList = (List<Map<String, Object>>) answer.get("answer");
                        if (Objects.nonNull(answerList) && answerList.size() > 0) {
                            for (Map<String, Object> option : answerList) {
                                List<String> itemList = (List<String>) item.get("data");
                                if (Objects.nonNull(option.get("answer")) && option.get("answer") instanceof List) {
                                    List<Map<String, Object>> ans = (List<Map<String, Object>>) option.get("answer");
                                    if (!CollectionUtils.isEmpty(ans)) {
                                        for (Map<String, Object> ansObj : ans) {
                                            if (ansObj.get("gid") instanceof Integer) {
                                                Integer gid1 = (Integer) ansObj.get("gid");
                                                if (itemList.contains(String.valueOf(gid1))) {
                                                    ansObj.put("marker", true);
                                                } else if (itemList.contains(gid1)) {
                                                    ansObj.put("marker", true);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (operation.equals(SurveyTitleTypeEnum.ORDER.getIndex())) {
                        // 排序处理
                        List<Integer> opList = new ArrayList<>();
                        List<Map<String, Object>> itemList = (List<Map<String, Object>>) item.get("data");
                        for (Map<String, Object> itemO : itemList) {
                            opList.add(Integer.parseInt(String.valueOf(itemO.get("gid"))));
                        }
                        if (answer.get("answer") instanceof List) {
                            List<Map<String, Object>> answerList = (List<Map<String, Object>>) answer.get("answer");
                            for (Map<String, Object> option : answerList) {
                                if (opList.contains(Integer.parseInt(String.valueOf(option.get("gid"))))) {
                                    option.put("marker", true);
                                }
                            }
                        }
                    }
                }
                // 敏感词合并设置
                if (!CollectionUtils.isEmpty(wordRangeList)) {
                    Map<String, List<Integer[]>> mergeData = new HashMap<>();
                    for (Object wr : wordRangeList) {
                        if (wr instanceof Map) {
                            checkUtil.mergeWordRange(mergeData, (Map<String, Object>) wr, (String) answer.get("qtype"));
                        }
                    }
                    if (mergeData.size() > 0) {
                        boolean marker = checkUtil.wordMarker(answer.get("answer"), mergeData, (String) answer.get("qtype"));
                        if (!marker) {
                            log.error("[Ticket] parse answer marker failed {},{}",
                                    answer.get("qtype"), answer.get("answer"));
                        }
                    }
                }

                // 设置 ruleList
                if (!CollectionUtils.isEmpty(ruleSet)) {
                    List<String> ruleList = new ArrayList<>(ruleSet);
                    answer.put("ruleList", ruleList);
                }
            }

            return answers;
        } catch (Exception e) {
            log.error("[Ticket] parse answer", e);
            return null;
        }
    }
}
